package com.wx.wechat.handler;

import com.alibaba.fastjson.JSON;
import com.google.gson.Gson;
import com.wx.wechat.Al.model.ApiModel;
import com.wx.wechat.Al.model.BaiduChatMessage;
import com.wx.wechat.Al.model.ErnieBotTurboResponse;
import com.wx.wechat.Al.model.ErnieBotTurboStreamParam;
import com.wx.wechat.Al.service.BaiduService;
import com.wx.wechat.redis.RedisUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.concurrent.TimeUnit;

/**
 * 文本类型处理器
 */
@Component
@Slf4j
public class ReceiveTextHandler implements WeChatMsgHandler{
    private static final String LOGIN_PREFIX = "loginCode";
    @Resource
    private RedisUtil redisUtil;
    @Resource
    private ApiModel apiModel;
    /**
     * 关注类型
     * @return
     */
    @Override
    public WxChatMsgTypeEnum getType() {
        return WxChatMsgTypeEnum.TEXT_MSG;
    }

    @Override
    public String dealMessage(Map<String, String> messageMap) {

        log.info("接收到文本消息事件");
        String content = messageMap.get("Content");
        String fromUserName = messageMap.get("FromUserName");
        String toUserName = messageMap.get("ToUserName");
        if (!"登录".equals(content)) {
            List<List> list = new ArrayList<>();
            //获取api服务
            BaiduService baiduService = new BaiduService(apiModel.getAPI_KEY(), apiModel.getSECRET_KEY());
            ErnieBotTurboStreamParam params = new ErnieBotTurboStreamParam();
            String messages = redisUtil.get(messageMap.get("ToUserName"));
            List<BaiduChatMessage> messagesList;
            if (StringUtils.isBlank(messages)){
                messagesList=new ArrayList<>();
            }else {
                messagesList = JSON.parseArray(messages, BaiduChatMessage.class);
            }
            BaiduChatMessage message = new BaiduChatMessage();
            message.setContent(content);
            message.setRole("user");
            messagesList.add(message);
            params.setMessages(messagesList);
            ErnieBotTurboResponse response = baiduService.ernieBotTurbo(params);
            String result = response.getResult();
            BaiduChatMessage messageAssistant = new BaiduChatMessage();
            messageAssistant.setRole("assistant");
            messageAssistant.setContent(result);
            messagesList.add(messageAssistant);
            String JsonMessageList = JSON.toJSONString(messagesList);
            redisUtil.setNx(messageMap.get("ToUserName"),JsonMessageList,5L,TimeUnit.MINUTES);
            log.info("存入redis：{}",JsonMessageList);
            String replyContent = "<xml>\n" +
                    "  <ToUserName><![CDATA[" + fromUserName + "]]></ToUserName>\n" +
                    "  <FromUserName><![CDATA[" + toUserName + "]]></FromUserName>\n" +
                    "  <CreateTime>12345678</CreateTime>\n" +
                    "  <MsgType><![CDATA[text]]></MsgType>\n" +
                    "  <Content><![CDATA[" + result + "]]></Content>\n" +
                    "</xml>";
            return replyContent;
        }


        Random random = new Random();
        int num = random.nextInt(1000);
        String numKey = redisUtil.buildKey(LOGIN_PREFIX, String.valueOf(num));
        redisUtil.setNx(numKey, fromUserName, 5L, TimeUnit.MINUTES);
        String numContent = "您当前的验证码是：" + num + "！ 5分钟内有效";
        String replyContent = "<xml>\n" +
                "  <ToUserName><![CDATA[" + fromUserName + "]]></ToUserName>\n" +
                "  <FromUserName><![CDATA[" + toUserName + "]]></FromUserName>\n" +
                "  <CreateTime>12345678</CreateTime>\n" +
                "  <MsgType><![CDATA[text]]></MsgType>\n" +
                "  <Content><![CDATA[" + numContent + "]]></Content>\n" +
                "</xml>";

        return replyContent;

    }
}


